const axios = require('axios');
const fs = require('fs');
const path = require('path');

// 配置
const config = {
  baseURL: 'http://localhost:3001',
  trackingId: 'track_7746e0cab7a84b2d846e1bc59354d5ff',
  token: 'your-auth-token-here' // 需要替换为实际的token
};

// 创建axios实例
const api = axios.create({
  baseURL: config.baseURL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${config.token}`
  }
});

// 日志函数
function log(message, level = 'INFO') {
  const timestamp = new Date().toISOString();
  console.log(`[${timestamp}] [${level}] ${message}`);
}

// 测试函数
async function testPVSystem() {
  log('开始测试PV管理系统...');
  
  try {
    // 1. 测试获取今日日志统计
    log('1. 测试获取今日日志统计');
    try {
      const statsResponse = await api.get('/tracking/logs/stats');
      log(`今日统计: ${JSON.stringify(statsResponse.data)}`, 'SUCCESS');
    } catch (error) {
      log(`获取统计失败: ${error.message}`, 'ERROR');
    }

    // 2. 测试获取业务闭环记录
    log('2. 测试获取业务闭环记录');
    try {
      const loopResponse = await api.get(`/tracking/logs/business-loop/${config.trackingId}`);
      log(`业务闭环记录数量: ${loopResponse.data.length}`, 'SUCCESS');
      
      if (loopResponse.data.length > 0) {
        log('最新记录:', 'INFO');
        console.log(JSON.stringify(loopResponse.data[loopResponse.data.length - 1], null, 2));
      }
    } catch (error) {
      log(`获取业务闭环记录失败: ${error.message}`, 'ERROR');
    }

    // 3. 测试检查业务闭环完整性
    log('3. 测试检查业务闭环完整性');
    try {
      const integrityResponse = await api.get(`/tracking/logs/business-loop/${config.trackingId}/integrity`);
      const integrity = integrityResponse.data;
      
      if (integrity.isComplete) {
        log('业务闭环完整', 'SUCCESS');
      } else {
        log(`业务闭环不完整，缺失步骤: ${integrity.missingSteps.join(', ')}`, 'WARN');
      }
      
      log(`总步骤数: ${integrity.steps.length}`, 'INFO');
    } catch (error) {
      log(`检查业务闭环完整性失败: ${error.message}`, 'ERROR');
    }

    // 4. 测试获取网站列表
    log('4. 测试获取网站列表');
    try {
      const websitesResponse = await api.get('/tracking/websites');
      log(`网站数量: ${websitesResponse.data.length}`, 'SUCCESS');
      
      if (websitesResponse.data.length > 0) {
        const website = websitesResponse.data.find(w => w.trackingId === config.trackingId);
        if (website) {
          log(`找到匹配的网站: ${website.name}`, 'SUCCESS');
          
          // 5. 测试获取嵌入代码
          log('5. 测试获取嵌入代码');
          try {
            const embedResponse = await api.get(`/tracking/websites/${website.id}/embed-code`);
            log('嵌入代码获取成功', 'SUCCESS');
            log(`脚本标签: ${embedResponse.data.scriptTag}`, 'INFO');
          } catch (error) {
            log(`获取嵌入代码失败: ${error.message}`, 'ERROR');
          }
        } else {
          log(`未找到跟踪ID为 ${config.trackingId} 的网站`, 'WARN');
        }
      }
    } catch (error) {
      log(`获取网站列表失败: ${error.message}`, 'ERROR');
    }

    // 6. 检查日志文件
    log('6. 检查日志文件');
    const logDir = path.join(__dirname, 'logs');
    if (fs.existsSync(logDir)) {
      const trackingLogDir = path.join(logDir, 'tracking');
      const businessLoopLogDir = path.join(logDir, 'business-loop');
      
      if (fs.existsSync(trackingLogDir)) {
        const trackingFiles = fs.readdirSync(trackingLogDir);
        log(`跟踪日志文件数量: ${trackingFiles.length}`, 'INFO');
        
        if (trackingFiles.length > 0) {
          const todayFile = `tracking-${new Date().toISOString().split('T')[0]}.log`;
          const todayFilePath = path.join(trackingLogDir, todayFile);
          
          if (fs.existsSync(todayFilePath)) {
            const content = fs.readFileSync(todayFilePath, 'utf8');
            const lines = content.split('\n').filter(line => line.trim());
            log(`今日跟踪日志条数: ${lines.length}`, 'INFO');
          }
        }
      }
      
      if (fs.existsSync(businessLoopLogDir)) {
        const businessLoopFiles = fs.readdirSync(businessLoopLogDir);
        log(`业务闭环日志文件数量: ${businessLoopFiles.length}`, 'INFO');
        
        if (businessLoopFiles.length > 0) {
          const todayFile = `business-loop-${new Date().toISOString().split('T')[0]}.log`;
          const todayFilePath = path.join(businessLoopLogDir, todayFile);
          
          if (fs.existsSync(todayFilePath)) {
            const content = fs.readFileSync(todayFilePath, 'utf8');
            const lines = content.split('\n').filter(line => line.trim());
            log(`今日业务闭环日志条数: ${lines.length}`, 'INFO');
          }
        }
      }
    } else {
      log('日志目录不存在', 'WARN');
    }

    // 7. 模拟页面访问请求
    log('7. 模拟页面访问请求');
    try {
      const pageviewData = {
        trackingId: config.trackingId,
        url: 'http://localhost:3001/test-page',
        title: '测试页面',
        referrer: 'http://localhost:3001/',
        sessionId: 'test-session-' + Date.now(),
        customData: {
          testEvent: 'manual_test',
          timestamp: new Date().toISOString()
        }
      };
      
      const pageviewResponse = await axios.post(`${config.baseURL}/tracking/pageview`, pageviewData, {
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      if (pageviewResponse.status === 200) {
        log('页面访问请求发送成功', 'SUCCESS');
      } else {
        log(`页面访问请求返回状态: ${pageviewResponse.status}`, 'WARN');
      }
    } catch (error) {
      log(`页面访问请求失败: ${error.message}`, 'ERROR');
    }

    log('PV管理系统测试完成', 'SUCCESS');
    
  } catch (error) {
    log(`测试过程中发生错误: ${error.message}`, 'ERROR');
  }
}

// 运行测试
if (require.main === module) {
  testPVSystem().then(() => {
    log('测试脚本执行完成');
    process.exit(0);
  }).catch(error => {
    log(`测试脚本执行失败: ${error.message}`, 'ERROR');
    process.exit(1);
  });
}

module.exports = { testPVSystem, log }; 